package com.fiveGroup.advice;

import com.fiveGroup.pojo.vo.DataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public DataVo handlerException (Exception e){
        log.error("全局异常捕获");
        e.printStackTrace();
        return DataVo.fail(500,e.getMessage());
    }


    //参数校验异常处理器
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public DataVo handlerMethodArgumentNotValidException (MethodArgumentNotValidException e){
        //判断校验是否成功 不成功有错误信息
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()) {
            //失败将对应属性校验失败信息写回前端
            HashMap<String, String> map = new HashMap<>();
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                //字段名称，字段错误信息
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return DataVo.fail(400,map.toString());

        }
        return null;
    }
}
